package com.kjj;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import android.content.Context;
import android.graphics.Bitmap;
import android.provider.Settings.Secure;

public class ProductList {

    private ArrayList<Map<String, Object>> mTable;
    private ArrayList<Product> mList;
    private KjjActivity mActivity;
    public static String phoneNum;
    public static String androidId;

    public ProductList(KjjActivity activity) {
	mActivity = activity;
	androidId = Secure.getString(mActivity.getContentResolver(),
		Secure.ANDROID_ID);
    }

    public boolean initList() {
	mTable = new ArrayList<Map<String, Object>>();
	mList = new ArrayList<Product>();
	return loadData();
    }

    public int getSize() {
	return mList.size();
    }

    public Product getProduct(int index) {
	return mList.get(index);
    }

    public ArrayList<Map<String, Object>> getTable() {
	return mTable;
    }

    public void addProduct(Product product) {
	Map<String, Object> item = new HashMap<String, Object>();
	for (int i = 0; i < 3; i++) {
	    if (product.pictures[i] != null) {
		item.put("image", product.pictures[i]);
		break;
	    }
	}
	item.put("price", "价格：" + product.price + "元");
	item.put("desc", product.description);
	mTable.add(item);

    }

    public void addItem(Bitmap[] picture, String[] url, String price,
	    String description) {
	Product product = new Product(picture, url, price, description);
	Communication.postProduct(null, product);
	mList.add(product);
	addProduct(product);
	saveData();
    }

    public void deleteItem(int position) {
	Communication.deleteProduct(mList.get(position));
	mList.remove(position);
	mTable.remove(position);
	saveData();
    }

    private boolean loadData() {
	for (int i = 0; i < getProductNum(); i++) {
	    Product product = new Product();
	    product.load(mActivity, i);
	    mList.add(product);
	    addProduct(product);
	}
	return true;
    }

    private boolean saveData() {
	saveProductNum();
	for (int i = 0; i < mList.size(); i++) {
	    mList.get(i).save(mActivity, i);
	}
	return true;
    }

    private void saveProductNum() {
	try {
	    Properties prop = new Properties();
	    prop.put("number", mList.size() + "");
	    FileOutputStream stream = mActivity.openFileOutput("product.num",
		    Context.MODE_PRIVATE);
	    prop.store(stream, "");
	} catch (Exception ex) {
	    ex.printStackTrace();
	}
    }

    private int getProductNum() {
	int num = 0;
	try {
	    Properties prop = new Properties();
	    FileInputStream stream = mActivity.openFileInput("product.num");
	    prop.load(stream);
	    num = Integer.parseInt(prop.getProperty("number", "0"));
	} catch (Exception ex) {
	    ex.printStackTrace();
	}
	return num;
    }
}
